package com.mingyuean.demo.mybatis.transaction.jdbc;

import com.mingyuean.demo.mybatis.session.TransactionIsolationLevel;
import com.mingyuean.demo.mybatis.transaction.Transaction;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author MingYueAn
 * <p>  Jdbc事务
 * <p>  2023/3/22 21:25
 * @version: 1.0
 */
public class JdbcTransaction implements Transaction {

    /**
     * 与事务关联的 Connection 对象。
     */
    protected Connection connection;

    /**
     * 与事务关联的 DataSource 对象。
     */
    protected DataSource dataSource;

    /**
     * 事务的隔离级别，默认为 NONE。
     */
    protected TransactionIsolationLevel level = TransactionIsolationLevel.NONE;

    /**
     * 是否自动提交事务，默认为 false。
     */
    protected boolean autoCommit;

    public JdbcTransaction(DataSource dataSource, TransactionIsolationLevel level, boolean autoCommit) {
        this.dataSource = dataSource;
        this.level = level;
        this.autoCommit = autoCommit;
    }

    public JdbcTransaction(Connection connection) {
        this.connection = connection;
    }

    @Override
    public Connection getConnection() throws SQLException {
        connection = dataSource.getConnection();
        connection.setAutoCommit(autoCommit);
        connection.setTransactionIsolation(level.getLevel());
        return connection;
    }

    @Override
    public void commit() throws SQLException {
        if (connection != null && !connection.getAutoCommit()) {
            connection.commit();
        }
    }

    @Override
    public void rollback() throws SQLException {
        if (connection != null && !connection.getAutoCommit()) {
            connection.rollback();
        }
    }

    @Override
    public void close() throws SQLException {
        if (connection != null && !connection.getAutoCommit()) {
            connection.close();
        }
    }
}
